'''
中华怡康少儿重大疾病保险
'''
import sys

sys.path.append('../..')
from common.config import *
from db.mysql import MysqlClient
from itertools import product
import requests, json
from common.helper import Helper


class Spider(object):
    def __init__(self):
        self.mysql = MysqlClient()
        self.name = "中华怡康少儿重大疾病保险"

    # 生成产品数据
    def genProductInfo(self):
        plan = {
            # 年龄段 0-17
            "year": [str(i) for i in range(0, 18)],
            # 性别 M 男 F 女
            "gender": ["M", "F"],
            # 缴费期间
            "interval": ["5", "10", "15", "20", "30"],
            # 保障期限
            "expire": ["终身"],
            # 保障金额
            "money": ["50000"],

        }
        for v in product(plan["year"], plan["gender"], plan["interval"], plan["expire"], plan["money"]):
            self.mysql.cursor.execute(domain[self.name]["insert_sql"].format(v[0], v[1], v[2], v[3], v[4]))
            self.mysql._conn.commit()
            print(domain[self.name]["insert_sql"].format(v[0], v[1], v[2], v[3], v[4]))

    # 执行爬虫
    def requestJson(self, dt=None, null=None):

        payload = {"insuredEntity": {"sex": "" + dt["gender"] + "",
                                     "birthday": "{year}-12-13".format(year=2019 - int(dt["year"]))},
                   "riskFactsList": [{"name": "factor_F0017B_017B20_insuYear", "key": "insuYear", "value": "105"},
                                     {"name": "factor_F0017B_017B20_amnt", "key": "amnt", "value": "50000"},
                                     {"name": "factor_F0017B_017B20_payIntv", "key": "payIntv", "value": "12"},
                                     {"name": "factor_F0017B_017B20_payEndYear", "key": "payEndYear", "value": dt["interval"]},
                                     {"name": "factor_F0017B_017B20_prem", "key": "prem", "value": ""}],
                   "productInfo": {"id": "297037078742363", "productCode": "F0017B", "name": "中华怡康终身重大疾病保险",
                                   "serverTime": "2020-01-13", "riskList": [
                           {"id": "291921278863016", "riskCode": "F0017B", "nameCn": "中华怡康终身重大疾病保险",
                            "mainCovRiderFlg": "M", "mult": null, "dutyList": [
                               {"dutyId": "291921636788412", "riskCode": "F0017B", "dutyCode": "017B20",
                                "dutyName": "中华怡康终身重大疾病保险", "choflg": "M", "vpu": "1000", "calmode": null, "mult": null,
                                "rate": null, "extProperties": null, "riskInputFactors": [
                                   {"key": "insuYear", "name": "保险期间", "comp": "SingleComboBox", "val": "105",
                                    "nullable": "true", "required": "false", "maxVal": "0", "minVal": "0", "desc": null,
                                    "dic": [{"v": "终身", "k": "105"}], "readonly": "true", "disabled": "true",
                                    "dataType": "P", "mod": "1", "dutyCode": "000101", "ctrlType": "P",
                                    "effacted": null},
                                   {"key": "amnt", "name": "保额", "comp": "SelectList", "val": "100000",
                                    "nullable": "true",
                                    "required": "false", "maxVal": "250000", "minVal": "50000", "desc": null,
                                    "dic": [{"v": "5万", "k": "50000"}, {"v": "10万", "k": "100000"},
                                            {"v": "15万", "k": "150000"}, {"v": "20万", "k": "200000"},
                                            {"v": "25万", "k": "250000"}], "readonly": "false", "disabled": "false",
                                    "dataType": "P", "mod": "1", "dutyCode": "000101", "ctrlType": "P",
                                    "effacted": null},
                                   {"key": "payIntv", "name": "交费间隔", "comp": "SingleComboBox", "val": "12",
                                    "nullable": "true", "required": "false", "maxVal": "0", "minVal": "0",
                                    "desc": "空白=表示有多项选择，需要从界面传入,有固定值=表示有唯一的交费间隔,=1=不定期缴费,0=趸缴1=月缴,3=季缴6=半年缴,12=年缴",
                                    "dic": [{"v": "年交", "k": "12"}], "readonly": "false", "disabled": "false",
                                    "dataType": "P", "mod": "1", "dutyCode": "000101", "ctrlType": "P",
                                    "effacted": null},
                                   {"key": "payEndYear", "name": "交费期间", "comp": "SingleComboBox", "val": "5",
                                    "nullable": "true", "required": "false", "maxVal": "0", "minVal": "0",
                                    "desc": "5=5年\n10=10年\n15=15年\n20=20年\n30=30年",
                                    "dic": [{"v": "5年", "k": "5"}, {"v": "10年", "k": "10"}, {"v": "15年", "k": "15"},
                                            {"v": "20年", "k": "20"}, {"v": "30年", "k": "30"}], "readonly": "false",
                                    "disabled": "false", "dataType": "P", "mod": "1", "dutyCode": "000101",
                                    "ctrlType": "P", "effacted": "insuredPeople_birthday"}]}],
                            "extProperties": [{"field": "RinsFlag", "name": "分保标记", "val": "N"},
                                              {"field": "RiskTypeDetail", "name": "险类标记", "val": "D"},
                                              {"field": "BonusFlag", "name": "分红标记", "val": "0"},
                                              {"field": "ListFlag", "name": "有无名单标记", "val": "Y"},
                                              {"field": "NeedGetPolDate", "name": "是否需录入客户签收日期", "val": "0"},
                                              {"field": "ProtocolFlag", "name": "协议险（赠送险）标记", "val": "N"},
                                              {"field": "InsuPeriodFlag", "name": "保险期限标志", "val": "0"},
                                              {"field": "SignDateCalMode", "name": "生效日算法", "val": "1"},
                                              {"field": "InsuredFlag", "name": "多被保人标记", "val": "S"},
                                              {"field": "BnfFlag", "name": "受益人标记", "val": "N"},
                                              {"field": "TempPayFlag", "name": "暂缴费标记", "val": "N"},
                                              {"field": "MortagageFlag", "name": "抵押标记", "val": "N"},
                                              {"field": "AutoPayFlag", "name": "能否自动垫缴标志", "val": "1"},
                                              {"field": "RnewFlag", "name": "自动续保标记（续保次数）", "val": "N"},
                                              {"field": "InvestFlag", "name": "投资标记", "val": "Y"}]}]}}

        r = requests.post(url=domain[self.name]["url"], headers=domain[self.name]["header"], data=json.dumps(payload))
        print( r.text )
        if r.status_code == 200 and "试算成功" in r.text:


            price = Helper.decimalParse(r.json()["data"]["ssResult"]["insurances"][0]["businessObj"]["originalPolicyPrem"])

            data = {
                "name":self.name,
                "id":dt["id"],
                "price":price
            }
            self.mysql.updatePrice( data )

        else:

            data = {
                "name":self.name,
                "id":dt["id"],
                "state":3
            }
            self.mysql.updateTask( data )


    def main(self):

        while True:

            # 随机领取一条数据
            dt = self.mysql.randTask(self.name)

            if not dt:
                print("产品价格抓取完成~~~")

                return

            # 任务执行状态
            data = {
                "name": self.name,
                "id": dt["id"],
                "state": 1
            }
            self.mysql.updateTask(data)
            self.requestJson( dt=dt)

